package com.hivision.iot.api;


import com.alibaba.fastjson.JSON;
import com.hivision.iot.dto.*;
import okhttp3.Response;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.net.MalformedURLException;
import java.net.URL;
import java.util.*;

/**
 * @program: CjxjyEquipment
 * @description: 阿里客户端 此类封装调用阿里api 使用方式：
 * 1、在别的模块引用 cjxjy-iot-ali
 * 2、通过 <<边缘侧 OpenApi文档>> 搜索具体的调用方法 (没有的话请自行封装方法和DTO)
 * @author: Dd7
 * @create: 2023-03-07 14:04
 *
 **/


@Service
public class AliReqClient {

    @Value("${alihttp.ipAddress}")
    private String host;

    @Autowired
    private AliClient aliClient;

    /**
     * 查询元数据
     * @param param param参数
     * @return
     */
    public AssetBaseDataResponseDTO getAssetBaseData(Map<String, Object> param){
        String uri = host.concat("/2021-06-10/assets");
        try {
            URL url = getURL(uri,param);
            Response response = aliClient.request("GET", url, null);
            AssetBaseDataResponseDTO assetBaseDataResponseDTO = JSON.parseObject(Objects.requireNonNull(response.body()).string(),AssetBaseDataResponseDTO.class);
            return assetBaseDataResponseDTO;
        }catch (Exception e){
            e.printStackTrace();
        }
        return null;
    }

    public AlarmsDTO getWarnInfo(Map<String, Object> param) {
        String uri = host.concat("/2021-06-10/alarmevents");
        try {
            URL url = getURL(uri,param);
            Response response = aliClient.request("GET", url, null);
            AlarmsDTO alarmsDTO = JSON.parseObject(Objects.requireNonNull(response.body()).string(),AlarmsDTO.class);
            return alarmsDTO;
        }catch (Exception e){
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 查询元数据状态
     * @param param param参数
     * @return
     */
    public AssetState getAssetState(Map<String,Object> param){
        String uri = host.concat("/2021-06-10/asset/state");
        try {
            URL url = getURL(uri,param);
            Response response = aliClient.request("GET", url, null);
            AssetState assetState = JSON.parseObject(Objects.requireNonNull(response.body()).string(),AssetState.class);
            return assetState;
        }catch (Exception e){
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 查询单个资产的技术属性值
     * @param assetCode
     * @param param
     * @return
     */
    public AssetTechnologyAttrResponseDTO getAssetTechnologyAttrData(String assetCode, Map<String,Object> param){
        String uri = String.format(host.concat("/2021-06-10/assets/%s/attributes"),assetCode);
        try {
            URL url = getURL(uri,param);
            Response response = aliClient.request("GET", url, null);
            AssetTechnologyAttrResponseDTO assetTechnologyAttrResponseDTO = JSON.parseObject(Objects.requireNonNull(response.body()).string(),AssetTechnologyAttrResponseDTO.class);
            return assetTechnologyAttrResponseDTO;
        }catch (Exception e){
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 查询连接和设备的映射关系
     * @return
     */
    public DriversConnDTO queryDriverConnAssetMap(){
        String uri = host.concat("/2021-06-10/driver-conn-asset-map");
        try {
            URL url = getURL(uri,null);
            Response response = aliClient.request("GET", url, null);
            DriversConnDTO driversConnDTO = JSON.parseObject(Objects.requireNonNull(response.body()).string(),DriversConnDTO.class);
            return driversConnDTO;
        }catch (Exception e){
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 查询连接列表
     * @param code 驱动编码
     * @return
     */
    public ConnectionInfoDTO getConnectionName(String code, Map<String, Object> params){
        String uri = String.format(host.concat("/2021-06-10/drivers/%s/connections/list"),code);
        try {
            URL url = getURL(uri,params);
            Response response = aliClient.request("GET", url, null);
            ConnectionInfoDTO connectionInfoDTO = JSON.parseObject(Objects.requireNonNull(response.body()).string(),ConnectionInfoDTO.class);
            return connectionInfoDTO;
        }catch (Exception e){
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 查询连接状态
     * @param code 驱动编码
     * @param params params参数
     * @return
     */
    public DriversConnState queryDriverConnState(String code,Map<String,Object> params){
        String uri = String.format(host.concat("/2021-06-10/drivers/%s/connections/state"),code);
        try {
            URL url = getURL(uri,params);
            Response response = aliClient.request("GET", url, null);
            DriversConnState driversConnState = JSON.parseObject(Objects.requireNonNull(response.body()).string(),DriversConnState.class);
            return driversConnState;
        }catch (Exception e){
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 更新属性值
     * @param attributeValueRequestDTO
     * @param bodyDTO
     * @return
     */
    public String patchAttributeValue(AttributeValueRequestDTO attributeValueRequestDTO){
        String uri = String.format(host.concat("/2021-06-10/assets/%s/attributes/%s"),attributeValueRequestDTO.getAssetCode(),attributeValueRequestDTO.getAttributeCode());
        try {
            URL url = getURL(uri,null);
            Map<String,String> map = new HashMap<>();
            map.put("Value",attributeValueRequestDTO.getValue());
            Response response = aliClient.request("PATCH", url, map);
            return String.valueOf(response.code());
        }catch (Exception e){
            e.printStackTrace();
        }
        return "10000";
    }



    /**
     * 拼接URL
     * @param uri 原host
     * @param param param参数
     * @return
     * @throws MalformedURLException
     */
    private URL getURL(String uri,Map<String, Object> param) throws MalformedURLException {

        if (param == null || param.size()==0){
            return new URL(uri);
        }

        StringBuilder url = new StringBuilder();
        url.append(uri).append("?");
        for (Map.Entry<String, Object> entry : param.entrySet()) {
            if (entry.getValue() != null) {
                if (entry.getValue() instanceof List<?>) {
                    ArrayList<String> entryValueList = (ArrayList<String>) entry.getValue();
                    for (int i = 0; i < entryValueList.size(); i++) {
                        url.append(entry.getKey()).append("=").append(entryValueList.get(i)).append("&");
                    }
                } else {
                    url.append(entry.getKey()).append("=").append(entry.getValue()).append("&");
                }
            }
        }
        String getUrl = url.substring(0, url.length() - 1);
        return new URL(getUrl);
    }
}
